package com.hj.springframework3.jdbc;

import com.hj.springframework3.annotation.Autowired;
import com.hj.springframework3.annotation.Bean;
import com.hj.springframework3.annotation.Configuration;
import com.hj.springframework3.annotation.Value;
import com.hj.springframework3.jdbc.tx.DataSourceTransactionManager;
import com.hj.springframework3.jdbc.tx.PlatformTransactionManager;
import com.hj.springframework3.jdbc.tx.TransactionalBeanPostProcessor;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;

/**
 * @Author : hujing
 * @Date: 2025/7/9 16:55
 * @Description: 数据库配置类
 */
@Configuration
public class JdbcConfiguration {
    
    @Bean(destroyMethod = "close")
    DataSource dataSource(
            @Value("${summer.datasource.url}") String url,
            @Value("${summer.datasource.username}") String username,
            @Value("${summer.datasource.password}") String password,
            @Value("${summer.datasource.driver-class-name}") String driverClassName,
            @Value("${summer.datasource.maximum-pool-size:20}") int maximumPoolSize,
            @Value("${summer.datasource.minimum-pool-size:1}") int minimumPoolSize,
            @Value("${summer.datasource.connection-timeout:30000}") int connectionTimeout
    ){
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(url);
        hikariConfig.setUsername(username);
        hikariConfig.setPassword(password);
        hikariConfig.setDriverClassName(driverClassName);
        hikariConfig.setMaximumPoolSize(maximumPoolSize);
        hikariConfig.setMinimumIdle(minimumPoolSize);
        hikariConfig.setConnectionTimeout(connectionTimeout);
        
        return new HikariDataSource(hikariConfig);
    }
    
    @Bean
    JdbcTemplate jdbcTemplate(@Autowired DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
    
    @Bean
    TransactionalBeanPostProcessor transactionalBeanPostProcessor(){
        return new TransactionalBeanPostProcessor();
    }
    
    @Bean
    PlatformTransactionManager platformTransactionManager(@Autowired DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}
